package com.rn.ddd.infrastructure.engine;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 执行引擎
 *
 * @author 然诺
 * @date 2022/3/6
 */
@Component
public class DefaultOrderEngine implements OrderEngine {

    @Autowired
    private DefaultStateProcessorRegistry stateProcessorRegistry;

    @Override
    public <T> Result<T> sendEvent(OrderEvent orderEvent) throws Exception {
        return null;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> Result<T> sendEvent(OrderEvent orderEvent, Order order) throws Exception {
        // 构建上下文
        StateContext context = getStateContext(orderEvent, order);
        // 获取处理器
        StateProcessor<T, ?> stateProcessor = getStateProcessor(context);
        // 执行逻辑处理
        return stateProcessor.execute(context);
    }

    @SuppressWarnings("unchecked")
    private <T> StateProcessor<T, ?> getStateProcessor(StateContext<?> context) {
        OrderEvent orderEvent = context.getOrderEvent();
        Order order = context.getOrder();
        List<AbstractStateProcessor> processorList = stateProcessorRegistry.getStateProcessors(
                order.getOrderState(), orderEvent.getEventType(), order.getBizType(), order.getSceneId());
        if (CollectionUtils.isEmpty(processorList)) {
            throw new RuntimeException("Not found processor");
        }
        return processorList.get(0);
    }

    private static StateContext<?> getStateContext(OrderEvent orderEvent, Order order) {
        StateContext<?> context = new StateContext<>();
        context.setOrderEvent(orderEvent);
        context.setOrder(order);
        return context;
    }
}
